package p2pproxy;

import android.os.Handler;
import android.os.Message;

import nfwx.analytics.BuildConfig;


public class P2PSBalancer {		
	private long _handle;
	private Handler _handler;
	public native void open(String []urls);
	public native void addUrls(String []urls, boolean removeNotInList);
	public native String getBestUrl(boolean randomIfNoBestDetected);
	public native String syncHostToUrl(String url, String hostUrl);
	
	private static final int RETRY_GET_URL_MSG=100;
	public native void close();
	static {
		try {
			//System.loadLibrary("p2psclient");
			System.loadLibrary(BuildConfig.SO_LIB);
		} catch(Error e) {
			e.printStackTrace();
		}
	}
	
	public P2PSBalancer()
	{
		_handler=new Handler(){
			@Override
			public void handleMessage(Message msg)
			{
				if(msg.what == RETRY_GET_URL_MSG)
				{
					getBestUrl((IOnGetBaseURLCallback)msg.obj, false);
				}
			}
		};
	}
		
	
	public void getBestUrl(IOnGetBaseURLCallback cb, boolean randomIfNoBestDetected)
	{
		String url=getBestUrl(randomIfNoBestDetected);
		
		if(null == url || url.equals(""))
		{
			Message msg =new Message();
			msg.obj=cb;
			msg.what=RETRY_GET_URL_MSG;
			_handler.sendMessageDelayed(msg, 100);
			return;
		}
		cb.onUrl(this,url);
	}
	public interface IOnGetBaseURLCallback
	{
		public void onUrl(P2PSBalancer balancer, String rsurl);
	}
	
}
